package com.blogsystem.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义认证成功处理器，根据用户角色实现登录后跳转不同页面
 */
@Component
public class CustomAuthentication extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        
        // 将用户权限列表转换为字符串集合进行角色判断
        boolean isAdmin = AuthorityUtils.authorityListToSet(authentication.getAuthorities())
                .contains("ROLE_ADMIN");

        // 根据用户角色设置不同的重定向URL
        if (isAdmin) {
            // 管理员用户跳转到管理仪表板
            setDefaultTargetUrl("/admin/dashboard");
        } else {
            // 普通用户跳转到首页
            setDefaultTargetUrl("/");
        }

        // 执行父类的默认处理逻辑（包括重定向操作）
        super.onAuthenticationSuccess(request, response, authentication);
    }
}
